<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div
        class="search-form divClass"
        v-if="headerShow"
        style="margin-top: 15px; display: inline-block"
      >
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="织布单号" label-col-flex="100px">
              <a-input
                allow-clear
                style="width: 200px"
                class="bacClass"
                placeholder=""
                v-model="pageData.planOrderCode"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item label="坯布编号" label-col-flex="100px">
              <a-input
                allow-clear
                style="width: 200px"
                class="bacClass"
                placeholder=""
                v-model="pageData.greyCode"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item label="坯布批号" label-col-flex="100px">
              <a-input
                allow-clear
                style="width: 200px"
                class="bacClass"
                placeholder=""
                v-model="pageData.greyBatchNo"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item label="机台号" label-col-flex="100px">
              <a-input
                allow-clear
                style="width: 200px"
                class="bacClass"
                placeholder=""
                v-model="pageData.machineCode"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item label="磅布(初检)时间" label-col-flex="100px">
              <a-range-picker
                popup-container="html"
                style="width: 280px"
                class="bacClass"
                v-model="pageData.fistSgcTime"
                @press-enter="huiche"
              />
            </a-form-item>
            <a-form-item label="落布时间" label-col-flex="100px">
              <a-range-picker
                popup-container="html"
                style="width: 290px"
                class="bacClass"
                v-model="pageData.scanTime"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar" style="float: right; margin-top: -30px">
          <Toolbar
            class="gesture"
            :items="['查询', '导出', '全部导出']"
            @select="selectHandler"
            @export="exports"
            @exportAll="exportAll"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: 100%"
          :defaultColDef="defaultColDef"
          :suppressCopyRowsToClipboard="true"
          class="ag-theme-alpine"
          :rowData="pageData.tableList"
          :columnDefs="tableColumns"
          :localeText="localeText1"
          @FilterChanged="FilterChangeds"
        >
        </AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys
      :page-size-options="pagingList1"
      :total="total"
      :page-size="size"
      :current="page"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
    />
  </pageTabelLayout>
</template>

<script lang="ts" setup>
import { post, get } from '@/api/http'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Button, Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../api/axios.config'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import { template } from 'lodash'
import { setupGlobalComponent } from '@/layouts'
import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import useAgGridFilterSelector from '@/utils/aggridFilterAllSelect'
import dayjs from 'dayjs'
import filedownload from 'js-file-download'
import { exportStyleExcel } from '@/api/Export2StyleExcel'
import setTableTotalRow from '@/utils/setTableTotalRow.ts'

const pageData: any = reactive({
  pageLoading: false,
  tableList: [],
  btnList: [],
  hejishuzu: [],
  planOrderCode: '',
  greyCode: '',
  greyBatchNo: '',
  machineCode: '',
  fistSgcTime: [],
  scanTime: [],
})
const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const aggridFs = useAgGridFilterSelector()
const total = ref(0)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
  page.value = val
  doRefresh()
}
function change1(val: any) {
  size.value = val
  doRefresh()
}
const headerShow = ref<boolean>(true)
const toFixedNum = (num: number) => {
  return parseFloat(num.toFixed(2))
}
//查询
function doRefresh() {
  pageData.pageLoading = true
  post({
    url: 'product/statement/getPlanOrderOutputDetail',
    data: {
      page: page.value,
      size: size.value,
      planOrderCode: pageData.planOrderCode,
      greyCode: pageData.greyCode,
      greyBatchNo: pageData.greyBatchNo,
      machineCode: pageData.machineCode,
      sgcStartTime: pageData.fistSgcTime ? pageData.fistSgcTime[0] : null,
      sgcEndTime: pageData.fistSgcTime ? pageData.fistSgcTime[1] : null,
      scanStartTime: pageData.scanTime ? pageData.scanTime[0] : null,
      scanEndTime: pageData.scanTime ? pageData.scanTime[1] : null,
    },
  })
    .then(({ data, code }: any) => {
      if (code === 200) {
        gridOption.value.setFilterModel(null)
        gridOption.value.setRowData(data.list)
        pageData.tableList = data.list
        total.value = data.total
        countRow(pageData.tableList)
      }
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading = false
    })
}

const selectHandler = () => {
  page.value = 1
  doRefresh()
}

const huiche = () => {
  doRefresh()
}

const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
}

// 表格
const gridOption = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
}
const tableColumns: any = [
  {
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
  },
  { headerName: '公司', field: 'firm', width: 150 },
  { headerName: '织布单号', field: 'planOrderCode', width: 150 },
  { headerName: '生产单号', field: 'weavingCode', width: 150 },
  { headerName: '客户订单号', field: 'customOrderNo', width: 150 },
  { headerName: '客户名称', field: 'customName', width: 150 },
  { headerName: '坯布编号', field: 'greyCode', width: 150 },
  { headerName: '坯布名称', field: 'greyName', width: 150 },
  { headerName: '坯布批号', field: 'greyBatchNo', width: 150 },
  { headerName: '主推商品', field: 'productColthCode', width: 150 },
  { headerName: '等级', field: 'level', width: 150 },
  { headerName: '机台号', field: 'machineCode', width: 150 },
  { headerName: '设备机型', field: 'machineType', width: 150 },
  { headerName: '订单机型', field: 'orderMachineType', width: 150 },
  { headerName: '匹号', field: 'horseNo', width: 150 },
  { headerName: '机布号', field: 'machineGreyCode', width: 150 },
  { headerName: '理论落布重量', field: 'standardWeight', width: 150 },
  { headerName: '磅布重量', field: 'actualWeight', width: 150 },
  { headerName: '次布重量', field: 'timeClothShareWeight', width: 150 },
  { headerName: '验后重量', field: 'posteriorWeight', width: 150 },
  { headerName: '扣米数', field: 'buttonMeterNum', width: 150 },
  { headerName: '针寸数', field: 'workDrum', width: 150 },
  { headerName: '值机工号1', field: 'dutPersonCode1', width: 150 },
  { headerName: '值机工1', field: 'dutPerson1', width: 150 },
  { headerName: '落布转数1', field: 'joinConvolution1', width: 150 },
  { headerName: '重量1', field: 'croppingWeight1', width: 150 },
  { headerName: '值机工号2', field: 'dutPersonCode2', width: 150 },
  { headerName: '值机工2', field: 'dutPerson2', width: 150 },
  { headerName: '落布转数2', field: 'joinConvolution2', width: 150 },
  { headerName: '重量2', field: 'croppingWeight2', width: 150 },
  { headerName: '验布工1', field: 'sgcPerson1', width: 150 },
  { headerName: '验布工2', field: 'sgcPerson2', width: 150 },
  { headerName: '疵点信息', field: 'defect', width: 150 },
  { headerName: '落布时间', field: 'scanTime', width: 150 },
  { headerName: '磅布(初检)时间', field: 'fistSgcTime', width: 150 },
  { headerName: '最后检验时间', field: 'lastSgcTime', width: 150 },
  { headerName: '检验最后修改人', field: 'lastSgcName', width: 150 },
  { headerName: '二维码', field: 'clothfiyCode', width: 150 },
  { headerName: '一维码', field: 'barCode', width: 150 },
  { headerName: '纱批信息', field: 'yarnInfo', width: 150 },
  { headerName: '验布班组', field: 'sgcDep', width: 150 },
  { headerName: '可配色称', field: 'colorName', width: 150 },
  { headerName: '花灰色号', field: 'colorNumber', width: 150 },
  { headerName: '尾落布', field: 'lastScan', width: 150 },
  {
    headerName: '坯布状态',
    field: 'greyState',
    width: 150,
    cellRenderer: (params: any) => {
      let val =
        params.value == 1
          ? '落布'
          : params.value == 2
          ? '待处理'
          : params.value == 3
          ? '已检验'
          : params.value == 4
          ? '修补未处理'
          : params.value == 5
          ? '修补中'
          : params.value == 6
          ? '降等中'
          : params.value == 7
          ? '待入次'
          : params.value == 8
          ? '已入次'
          : params.value == 9
          ? '已处理'
          : params.value == 10
          ? '已入库'
          : params.value == 11
          ? '已出库'
          : ''
      return '<span>' + val + '</span>'
    },
    filterParams: {
      valueFormatter: function (params: any) {
        return params.value == 1
          ? '落布'
          : params.value == 2
          ? '待处理'
          : params.value == 3
          ? '已检验'
          : params.value == 4
          ? '修补未处理'
          : params.value == 5
          ? '修补中'
          : params.value == 6
          ? '降等中'
          : params.value == 7
          ? '待入次'
          : params.value == 8
          ? '已入次'
          : params.value == 9
          ? '已处理'
          : params.value == 10
          ? '已入库'
          : params.value == 11
          ? '已出库'
          : ''
      },
    },
  },
  { headerName: '原料信息', field: 'staple', width: 150 },
  { headerName: '备注', field: 'remark', width: 150 },
  { headerName: '是否修补', field: 'isCheckoutState', width: 150 },
  // { headerName: '尾落布', field: 'billDate', width: 150 }
]

//导出
const exports = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return
  }
  let header = tableColumns.map((o: any) => {
    return o.headerName
  })
  let filterCols = tableColumns.map((c: any) => {
    return c.field
  })
  let data = formatJson(filterCols, gridOption.value.getSelectedRows())
  exportStyleExcel({ header, data, filename: '订单产量明细表.xlsx' })
}

const formatJson = (filterVal: any, jsonData: any) => {
  return jsonData.map((v: any) =>
    filterVal.map((j: any) => {
      if (!v[j]) {
        return ''
      } else {
        return v[j]
      }
    })
  )
}

//全部导出
const exportAll = () => {
  post({
    url: '/product/statement/exportGetPlanOrderOutputDetail',
    data: {
      planOrderCode: pageData.planOrderCode,
      greyCode: pageData.greyCode,
      greyBatchNo: pageData.greyBatchNo,
      machineCode: pageData.machineCode,
      sgcStartTime: pageData.fistSgcTime ? pageData.fistSgcTime[0] : '',
      sgcEndTime: pageData.fistSgcTime ? pageData.fistSgcTime[1] : '',
      scanStartTime: pageData.scanTime ? pageData.scanTime[0] : '',
      scanEndTime: pageData.scanTime ? pageData.scanTime[1] : '',
    },
    responseType: 'blob',
  }).then((res: any) => {
    filedownload(res, '订单产量明细表.xlsx')
  })
}
function tableToXlsx(head: any, filename: any, body: any) {
  const uri = 'data:application/vnd.ms-excel;base64,',
    template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

  const a = document.createElement('a')
  a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
  a.download = filename
  a.click()
  document.removeChild(a)
}

//底部合计
const countRow = (data: any) => {
  setTableTotalRow(gridOption, data, [
    'standardWeight',
    'actualWeight',
    'timeClothShareWeight',
    'posteriorWeight',
    'buttonMeterNum',
    'joinConvolution1',
    'croppingWeight1',
    'joinConvolution2',
    'croppingWeight2',
  ])
}

//筛选
const FilterChangeds = (params: any) => {
  aggridFs.onFilterChanged(params)
  let data: any = {
    list: [],
  }
  params.api.forEachNodeAfterFilter((row: any) => {
    data.list.push(row.data)
  })
  countRow(data.list)
}

onMounted(() => {
  pageData.fistSgcTime = [
    dayjs(new Date()).format('YYYY-MM-DD'),
    dayjs(new Date()).format('YYYY-MM-DD'),
  ]
  doRefresh()
})
</script>
<style scoped>
:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}
</style>
